<?php

namespace api\modules\backend\models;

use Yii;
use \yii\db\ActiveRecord;
use common\commands\Common;

/**
 * Member Share Code Model
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class MemberShareCode extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%member_share_code}}';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['member_share_code_id'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['share_code'], 'required'],
            [['share_code'], 'unique']
        ];
    }

    public static function response($data)
    {
        header('Content-Type: application/json; charset=' . Yii::$app->charset);
        exit(json_encode($data));
    }

    /**
     * 生成分享码
     * @return bool|mixed|string
     */
    public function generateShareCode()
    {
        $share_code = substr(md5(uniqid(mt_rand(1000, 9999), true)), 26);

        $memberShareCodeResult = self::find()->select('member_share_code_id')
            ->where(['share_code' => $share_code])
            ->asArray()
            ->one();

        if (!empty($memberShareCodeResult)) {
            return static::generateShareCode();
        }

        $this->share_code = $share_code;
        $this->create_time = time();

        if (!self::validate()) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED')));
        }

        if (!$this->save()) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', 'DATABASE_FAILED')));
        }

        return $this->member_share_code_id;
    }
}
